import React, {
    Component
} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Dimensions,
    ScrollView,
    TouchableOpacity,
    ImageBackground,
    Image,
    TextInput
} from 'react-native';
import Util from './utils'
import Orientation from 'react-native-orientation';

export default class HomeScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            list:[],
            activeIndex:1,
            show:false,
            ip:''
        }
    }
    static navigationOptions = {
        header: null,
        gesturesEnabled: false,
    };
    componentDidMount() {
        Orientation.lockToLandscape();
        Orientation.lockToLandscape();

        Orientation.lockToLandscape();
        let list =[]
        for(let i =1;i<=12;i++){
            if(i==1){
                list.push({index:i,checked:true})
            }else{
                list.push({index:i,checked:false})
            }
        }
        this.setState({
            list:list
        })
        this.getIp()

    }
    componentWillMount(){
        Orientation.lockToLandscape();
        Orientation.lockToLandscape();
        Orientation.lockToLandscape();
    }
    onPressCompetition(item){
        let list =[]
        for(let i =1;i<=12;i++){
            list.push({index:i,checked:false})
        }
        let data =list
        if(data.length>0){
            data[item.index-1].checked=!data[item.index-1].checked
            this.setState({
                list:data,
                activeIndex:item.index
            })
        }
        this.getData(item.index)

    }
    _renderCompetitionItem(item){
        return  (
            <TouchableOpacity onPress={()=>this.onPressCompetition(item)}>
            <View style={[styles.competition,item.checked?{backgroundColor:'#003365'}:{}]}>
                <Text style={[styles.competitionText,item.checked?{color:'#ffffff'}:{}]}>{item.index}场</Text>
            </View>
            </TouchableOpacity>
    );
    }
    _renderCompetition(){
 
        if(this.state.list){
            return this.state.list.map( item => this._renderCompetitionItem(item) );
        }
    }
    _renderTopicItem(item){
        let info =""
        let rightAnser=""
        for(let i=0;item.options&&i<item.options.length;i++){
            if(item.type=="单选题"){
                info=info+item.options[i].answerOption +"、"+item.options[i].answerContent
                if(item.options[i].isRight=="1"){
                    rightAnser=rightAnser+item.options[i].answerOption +"、"+item.options[i].answerContent
                }
            }else{
                info=info+item.options[i].answerOption+"   "
                if(item.options[i].isRight=="1"){
                    rightAnser=rightAnser+"   "+item.options[i].answerOption
                }
            }

        }
        return  (
            <TouchableOpacity onPress={()=>this.onPressTopicItem(item)}>
                <View style={[styles.topic,item.id==this.state.activeQuestIndex?{borderColor:'#003365'}:{}]}>
                    <Text style={[styles.topicText]}>{item.stem}</Text>
                    <Text style={[styles.topicFF00]}>{info}</Text>
                    <Text style={[styles.topicAnswer]}>正确答案:{rightAnser}</Text>
                </View>
            </TouchableOpacity>
        );
    }
    _renderTopic(){
        if(this.state.questList){
            return this.state.questList.map( item => this._renderTopicItem(item) );
        }
    }
    onPressTopicItem(item){
        this.setState({
            activeQuestIndex:item.id,
            desc:item.explanation
        })
    }
    getIp(){
        let that=this
        storage.load({
            key: 'userinfo',
            // autoSync(默认为true)意味着在没有找到数据或数据过期时自动调用相应的sync方法
            autoSync: true,
            // syncInBackground(默认为true)意味着如果数据过期，
            // 在调用sync方法的同时先返回已经过期的数据。
            // 设置为false的话，则始终强制返回sync方法提供的最新数据(当然会需要更多等待时间)。
            syncInBackground: true,
            // 你还可以给sync方法传递额外的参数
            syncParams: {
                extraFetchOptions: {
                    // 各种参数
                },
                someFlag: true,
            },
        }).then(async ret => {
            if (ret.ip == undefined) {
            } else {
                that.setState({
                    ip: ret.ip ,
                })
                that.getData(1)

            }
        }).catch(err => {
            console.log(err)
        })
    }
    getData(id){
        console.log(id)
        let questList = []
        let url = `http://${this.state.ip}:10081/api/getQuestionForGuest?competition=${id}`//人力
        let that =this
        Util.get(url, (result) => {
            if(result&&result.length>0){
                let results=[]
                // result.map((resultItem)=>{
                //     if(resultItem.type!="投票题"){
                //         results.push(resultItem)
                //     }
                // })
                that.setState({
                    questList:result,
                    desc:result[0].explanation,
                    activeQuestIndex:result[0].id,
                    allquestList:result
                })
            }else{
                that.setState({
                    questList:[],
                    desc:"",
                    activeQuestIndex:"",
                    allquestList:""
                })
            }
        },(error)=>{
            console.log(error)
        })
      }
      _onPressshow(){
        this.setState({
            show:!this.state.show
        })
    }
    render() {
        return (
            <View style={[styles.flex]}>
                {/* <ImageBackground source={require('./image/mainback.png')} style={{width:Dimensions.get('window').width,height:Dimensions.get('window').height-25}} resizeMode='stretch'> */}
                    <View style={[styles.box]}>
                        <View style={[styles.boxstyle]}>
                            <Image source={require('./image/logo.png')} style={[styles.imgStyle]}></Image>
                            <Text style={[styles.headerFont]}>少年国学派第{this.state.activeIndex}场</Text>
                            <TouchableOpacity onPress={this._onPressshow.bind(this)} style={[styles.ipsetarea]}>
                                <Text></Text>
                            </TouchableOpacity>
                            {this.state.show?
                            <TextInput
                            style={{height: 40,width:300}}
                            placeholder="请输入用户名"
                            onChangeText={(text) => {
                                storage.save({
                                    key: 'userinfo', // 注意:请不要在key中使用_下划线符号!
                                    data: {
                                        ip:text
                                    }
                                });
                                this.setState({ip:text})
                                //this.getData(this.state.activeIndex)
                                }
                            }
                            value={this.state.ip}
                            placeholderTextColor='#A9A9A9'
                            underlineColorAndroid="transparent"
                            />:null}
                        </View>
                        <View style={[styles.mainList]}>
                            <View style={[styles.cloum1]}>
                                <ScrollView contentContainerStyle={[styles.cloumscroll]}>
                                {this._renderCompetition()}
                                </ScrollView>
                            </View>
                            <View style={[styles.cloum2]}>
                                <ScrollView contentContainerStyle={[styles.cloum2scroll]}>
                                    {this._renderTopic()}
                                </ScrollView>
                            </View>
                            <View style={[styles.cloum3]}>
                            <ScrollView contentContainerStyle={[styles.cloum3scroll]}>
                                    <Text>{this.state.desc}</Text>
                                </ScrollView>
                            </View>
                        </View>

                    </View>
                {/* </ImageBackground> */}
        </View>
        )
    }
}
const styles = StyleSheet.create({
    flex:{
        flex: 1,
        backgroundColor:'#ffffff',
    },
    box: {
      margin: 10,
      height:Dimensions.get('window').height-100
    },
    imgStyle:{
        width:50,
        height:50,
        position:'absolute',
    },
    boxstyle:{
        borderColor: '#989898',
        borderWidth: 1,
        height:60,
        borderRadius: 5,
        justifyContent:'flex-start',
         alignItems:'center',
        flexDirection:'row'
    },
    headerFont:{
        fontSize:24,
        marginLeft: 80,
    },
    mainList:{
        borderColor: '#989898',
        flexDirection: 'row', 
        marginTop: 10,
        // backgroundColor:'#d00'
    },
    cloum1:{
        height:Dimensions.get('window').height-130,
        width:75,
        borderColor: '#989898',
        borderWidth: 1,  
        borderRadius:5,
    },
    cloumscroll:{
        width:75,
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 0,  
    },
    cloum2:{
        height:Dimensions.get('window').height-130,
        width:415,
        borderColor: '#989898',
        borderWidth: 1,  
        borderRadius:5 ,
        backgroundColor:'#f2f2f2'

    },
    cloum2scroll:{
        width:415,
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 0,  
        backgroundColor:'#ffffff',

    },
    cloum3:{
        height:Dimensions.get('window').height-130,
        borderColor: '#989898',
        borderWidth: 1,   
        borderRadius:5,
        width:Dimensions.get('window').width/2,
        backgroundColor:'#f2f2f2'

    },
    cloum3scroll:{
        borderColor: '#989898',
        borderWidth: 1,  
        margin: 10, 
        backgroundColor:'#ffffff',
        height:Dimensions.get('window').height-150,
        borderRadius:5,

    },
    competition:{
        borderColor: '#003365',
        borderWidth: 1,   
        height:40,
        width:60,
        margin:3,
        borderRadius:10,
        justifyContent:'center',
        alignItems:'center',
    },
    competitionText:{
        color:'#003365',
        fontWeight: 'bold',
    },
    topicText:{
        color:'#000000',
    },
    topicAnswer:{
        color:'#d00000',

    },
    topicFF00:{
        color:'#4A4AFF',

    },
    ipsetarea:{
        width:200,
        height:60,
       // backgroundColor:'#ff0'
    },
    topic:{
        width:400,
        // backgroundColor:'#ff0',
        borderColor: '#989898',
        borderWidth: 1,  
        minHeight: 100,
        margin:5,
        borderRadius:5
    }
})